package com.example.task1.ui.AllService.garbage;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.bean.CommentBean;
import com.example.task1.bean.GarbageNewsDetailBean;
import com.example.task1.http.Api;
import com.example.task1.ui.base.NewsDetailsAdapter;
import com.example.task1.util.ApiResp;
import com.example.task1.util.ApiUtils;
import com.example.task1.util.CallBack;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class GarbageNewsDetailsActivity extends AppCompatActivity {

    private TextView tvTitle;
    private TextView tvTime;
    private TextView tvRead;
    private TextView tvContent;
    private TextView tvCommentNum;
    private RecyclerView rvComment;
    private boolean isTrue = true;
    private ProgressBar bar;
    private int pageNum;
    private LinearLayoutManager linearLayoutManager;
    private NewsDetailsAdapter newsDetailsAdapter;
    private static final String TAG = "NewsDetailsActivity";
    private NestedScrollView nest;
    private int id;
    private TextView end;
    private ImageView image;
    private EditText etComment;
    private Button btnSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_details);
        ActionBar supportActionBar = getSupportActionBar();
        supportActionBar.setTitle("新闻详情");
        supportActionBar.setDisplayHomeAsUpEnabled(true);
        initView();
        initData();
        setAdapter();
        loadCommentList();
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> map = new HashMap<>();
                String s = etComment.getText().toString();
                if (TextUtils.isEmpty(s)) {
                    etComment.setError("不能为空");
                } else {
                    map.put("newsId", id);
                    map.put("content", s);
                    Call<ApiResp> post = Api.api().post(MyApplication.TOKEN, "/prod-api/api/garbage-classification/news-comment", Api.getBody(map));
                    Api.send(post, ApiResp.class, new CallBack<ApiResp>() {
                        @Override
                        public void success(ApiResp data) {
                            MyApplication.show("评论成功");
                            etComment.setText("");
                            CommentBean.RowsDTO rowsDTO = new CommentBean.RowsDTO();
                            rowsDTO.setContent(s);
                            newsDetailsAdapter.addData(rowsDTO);
                        }

                        @Override
                        public void error(String msg) {

                        }
                    });

                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void loadCommentList() {
        rvComment.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                Log.d(TAG, "onScrollStateChanged: " + linearLayoutManager.findLastVisibleItemPosition());
                if (newsDetailsAdapter.getItemCount() - 1 == linearLayoutManager.findLastVisibleItemPosition() && isTrue) {
                    isTrue = false;
                    getCommentList(id);
                    bar.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void setAdapter() {
        newsDetailsAdapter = new NewsDetailsAdapter();
        linearLayoutManager = new LinearLayoutManager(this);
        newsDetailsAdapter.setHasStableIds(true);
        rvComment.setLayoutManager(linearLayoutManager);
        rvComment.setAdapter(newsDetailsAdapter);
    }

    private void initData() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        MyApplication.getApiService().get(MyApplication.TOKEN, "/prod-api/api/garbage-classification/news/" + id).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Gson gson = new Gson();
                    GarbageNewsDetailBean newsDetailsBean = gson.fromJson(string, GarbageNewsDetailBean.class);
                    if (newsDetailsBean.getCode() == 200) {
                        GarbageNewsDetailBean.DataDTO data = newsDetailsBean.getData();
                        setData(data);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {

            }
        });
        getCommentList(id);
    }

    private void getCommentList(int id) {
        MyApplication.getApiService().get(MyApplication.TOKEN, "/prod-api/api/garbage-classification/news-comment/list?newsId=" + id + "&pageNum=" + pageNum + "&pageSize=" + ApiUtils.pageSize).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Gson gson = new Gson();
                    CommentBean commentBean = gson.fromJson(string, CommentBean.class);
                    if (commentBean.getCode() == 200) {
                        tvCommentNum.setText(commentBean.getTotal() + "条评论");
                        if (newsDetailsAdapter.getData().size() < commentBean.getTotal()) {
                            newsDetailsAdapter.setData(commentBean.getRows());
                            pageNum++;
                            isTrue = true;
                        } else {
                            MyApplication.show("没有更多数据了~");
                        }
                        bar.setVisibility(View.GONE);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {

            }
        });
    }

    private void setData(GarbageNewsDetailBean.DataDTO data) {
        tvTitle.setText(data.getTitle());
        tvTime.setText(data.getCreateTime());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Spanned spanned = Html.fromHtml(data.getContent(), new Html.ImageGetter() {
                    @Override
                    public Drawable getDrawable(String source) {
                        try {
                            Drawable fromStream = Glide.with(GarbageNewsDetailsActivity.this).load(MyApplication.BASE_URL + source).submit().get();
                            int intrinsicWidth = fromStream.getIntrinsicWidth();
                            int intrinsicHeight = fromStream.getIntrinsicHeight();
                            fromStream.setBounds(0, 0, (1200 / intrinsicWidth) * intrinsicWidth, (900 / intrinsicHeight) * intrinsicHeight);
                            return fromStream;
//                          InputStream inputStream = (InputStream) new URL(MyApplication.BASE_URL + source).getContent();
//                          Drawable fromStream = Drawable.createFromStream(inputStream,"src");
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                }, null);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvContent.setText(spanned);
                        nest.smoothScrollTo(0, 0);
                    }
                });
            }
        }).start();
        MyApplication.glide(image, data.getImgUrl());
    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvRead = (TextView) findViewById(R.id.tv_read);
        tvContent = (TextView) findViewById(R.id.tv_content);
        tvCommentNum = (TextView) findViewById(R.id.tv_commentNum);
        rvComment = (RecyclerView) findViewById(R.id.rv_comment);
        bar = (ProgressBar) findViewById(R.id.bar);
        nest = (NestedScrollView) findViewById(R.id.nest);
        end = (TextView) findViewById(R.id.end);
        image = (ImageView) findViewById(R.id.image);
        etComment = findViewById(R.id.et_comment);
        btnSend = findViewById(R.id.btn_send);
    }
}